<template>
  <!-- 顶部组件 -->
  <div class="Header-box">
    <ul>
      <li style="margin-left: 0px; cursor: pointer" @click="goHome">
        <img
          src="http://127.0.0.1:9090/xuecheng-images/asset-logoIco.png"
          alt="LOGO"
        />
      </li>
      <li>
        <ul class="content">
          <li>
            <router-link style="text-decoration: none" to="#" class="home"
              ><span style="font-size: 16px" class="active"
                >首页</span
              ></router-link
            >
          </li>
          <li>
            <router-link style="text-decoration: none" to="#" class="home"
              ><span style="font-size: 16px" class="active"
                >课程</span
              ></router-link
            >
          </li>
          <li>
            <router-link style="text-decoration: none" to="#" class="home"
              ><span style="font-size: 16px" class="active"
                >职业规划</span
              ></router-link
            >
          </li>
        </ul>
      </li>
      <li class="search">
        <input type="text" placeholder="请输入关键词" class="input" />
        <div class="button">
          <span>
            <svg
              t="1699463372540"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="2764"
              width="200"
              height="200"
            >
              <path
                d="M416 192C537.6 192 640 294.4 640 416S537.6 640 416 640 192 537.6 192 416 294.4 192 416 192M416 128C256 128 128 256 128 416S256 704 416 704 704 576 704 416 576 128 416 128L416 128z"
                fill="#ffffff"
                p-id="2765"
              ></path>
              <path
                d="M832 864c-6.4 0-19.2 0-25.6-6.4l-192-192c-12.8-12.8-12.8-32 0-44.8s32-12.8 44.8 0l192 192c12.8 12.8 12.8 32 0 44.8C851.2 864 838.4 864 832 864z"
                fill="#ffffff"
                p-id="2766"
              ></path>
            </svg>
          </span>
        </div>
      </li>
      <li>
        <div v-if="this.isLogin" class="userInfo">
          <el-dropdown @command="setVisibleTrue">
            <div class="profile">
              <img
                :src="profile.images"
                style="width: 42px; height: 42px"
                alt="头像"
              />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="username">修改用户名</el-dropdown-item>
              <el-dropdown-item command="password">修改密码</el-dropdown-item>
              <el-dropdown-item command="phone">修改手机号</el-dropdown-item>
              <el-dropdown-item command="profile">更改头像</el-dropdown-item>
              <el-dropdown-item command="history">历史头像</el-dropdown-item>
              <el-dropdown-item command="exit">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="name">{{ profile.username }}</div>
        </div>
        <div class="userInfo" v-else>
          <div style="margin-right: 20px">
            <router-link class="login" to="/login">登录</router-link>
          </div>
          <div style="margin-right: 20px">|</div>
          <div>
            <router-link class="login" to="/register">注册</router-link>
          </div>
        </div>
      </li>
      <li style="margin-top: 15px">
        <span
          class="my"
          style="font-size: 16px; margin-right: 15px; display: inline-block"
          >我的学习</span
        >
        <span
          class="my"
          style="font-size: 16px; display: inline-block"
          @click="goCourseList"
          >教学机构</span
        >
      </li>
    </ul>
    <!-- 修改用户名 -->
    <el-dialog
      :show-close="false"
      title="修改用户名"
      :visible.sync="usernameVisible"
    >
      <el-form :model="user">
        <el-form-item label="用户名">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="usernameVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUsernameCommit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改用户名 -->
    <!-- 修改密码 -->
    <el-dialog
      :show-close="false"
      title="修改密码"
      :visible.sync="passwordVisible"
    >
      <el-form :model="user">
        <el-form-item label="输入原始密码">
          <el-input
            v-model="user.oldPassword"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="输入新密码">
          <el-input
            v-model="user.password"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input
            v-model="user.checkPassword"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePasswordCommit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <!-- 修改手机号 -->
    <el-dialog
      :show-close="false"
      title="修改手机号"
      :visible.sync="phoneVisible"
    >
      <span
        style="
          color: #ccc;
          font-size: 14px;
          margin-bottom: 20px;
          display: inline-block;
        "
        >为了确保账号的安全性，请输入原始手机验证码和新手机号码及验证码</span
      >
      <el-form :model="user">
        <el-form-item label="原始手机号">
          <el-input
            :disabled="true"
            style="width: 250px; margin-right: 15px"
            v-model="user.oldPhoneHide"
            autocomplete="off"
          ></el-input>
          <el-button
            :disabled="!user.OldCodeFlag"
            @click="sendOldSmsCode"
            type="success"
            >{{ user.OldCodeText }}</el-button
          >
          <el-input
            style="width: 150px; margin-left: 40px"
            v-model="user.oldSmsCodeInput"
            placeholder="验证码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新手机号">
          <el-input
            style="width: 250px; margin-right: 15px"
            v-model="user.newPhone"
            autocomplete="off"
          ></el-input>
          <el-button
            :disabled="!user.NewCodeFlag"
            @click="sendNewSmsCode"
            type="success"
            >{{ user.NewCodeText }}</el-button
          >
          <el-input
            style="width: 150px; margin-left: 40px"
            v-model="user.newSmsCodeInput"
            placeholder="验证码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="phoneVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePhoneCommit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改手机号 -->
    <!-- 修改头像 -->
    <el-dialog
      :show-close="false"
      title="修改用户头像"
      :visible.sync="profileVisible"
    >
      <div style="margin-bottom: 30px">
        请上传一张用户图像。注：1.重复上传，之前上传的头像会被覆盖 2.
        切勿上传超过2MB文件
      </div>
      <el-upload
        class="avatar-uploader"
        action="/api/v1/user/auth/profile/uploadProfile"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateProfileCancel">取 消</el-button>
        <el-button type="primary" @click="updateProfileCommit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改头像 -->
    <!-- 历史头像 -->
    <el-dialog
      :show-close="false"
      title="历史头像"
      :visible.sync="historyProfileVisible"
    >
      <el-radio-group v-model="checkProfile">
        <el-radio
          style="margin-top: 10px; margin-bottom: 10px"
          v-for="(item, index) in historyProfileList"
          :key="index"
          :label="index"
          ><img :src="item" style="width: 100px; height: 100px"
        /></el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="historyProfileCancel">取 消</el-button>
        <el-button type="primary" @click="historyProfileCommit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 历史头像 -->
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import http_user from '@/https/user/auth/user'
import http_register from '@/https/user/auth/register'
import http_profile from '@/https/user/auth/profile'
export default {
  data() {
    return {
      //  是否登录
      isLogin: true,
      // 用户头像信息
      profile: {
        username: '',
        images: '',
      },
      // 修改用户信息的实体
      user: {
        username: '',
        oldPassword: '',
        password: '',
        checkPassword: '',
        oldPhone: '',
        oldPhoneHide: '',
        newPhone: '',
        oldSmsCodeInput: '',
        newSmsCodeInput: '',
        oldSmsCode: '',
        newSmsCode: '',
        OldCodeFlag: true,
        NewCodeFlag: true,
        OldCodeText: '验证码',
        NewCodeText: '验证码',
      },
      // 是否显示修改用户名对话框
      usernameVisible: false,
      // 是否显示修改密码对话框
      passwordVisible: false,
      // 是否显示修改电话对话框
      phoneVisible: false,
      // 是否显示修改头像对话框
      profileVisible: false,
      // 修改头像数据
      imageUrl: '', //上传成功的图片路径
      imageList: [], //头像列表
      // 修改头像数据
      // 历史头像数据
      // 历史头像对话框是否可见
      historyProfileVisible: false,
      // 历史头像列表
      historyProfileList: [],
      // 选中的历史头像序列
      checkProfile: 0,
      // 历史头像数据
    }
  },
  methods: {
    // 跳转到home首页
    goHome() {
      if (!(this.$route.path === '/home')) {
        this.$router.push('/home')
      }
    },
    // 从cookie中获得用户信息
    getCookeieUserInfo() {
      const info = Cookies.get('userInfo')
      if (info !== undefined) {
        const infoObj = JSON.parse(info)
        Cookies.set('userInfo', info, { expires: 60 })
        return infoObj
      } else {
        return undefined
      }
    },
    // 修改cookie的信息
    setCookeieUserInfo(updateName, updateData) {
      const result = JSON.parse(Cookies.get('userInfo'))
      if (result !== undefined) {
        result[updateName] = updateData
      }
      Cookies.set('userInfo', JSON.stringify(result), { expires: 60 })
    },
    // 修改用户信息的弹窗设置
    async setVisibleTrue(command) {
      switch (command) {
        case 'username':
          this.usernameVisible = true
          this.user.username = this.profile.username
          break
        case 'password':
          this.passwordVisible = true
          break
        case 'phone':
          this.user.oldSmsCodeInput = ''
          this.user.newSmsCodeInput = ''
          this.user.newSmsCode = ''
          this.user.oldSmsCode = ''
          this.user.newPhone = ''
          this.phoneVisible = true
          const userIf = this.getCookeieUserInfo()
          const result = await http_user.getUserInfo(userIf.userId)
          if (result.data.code === 200) {
            this.user.oldPhone = result.data.data.phone
            this.user.oldPhoneHide = this.hidePhone(this.user.oldPhone)
          } else {
            this.$message.error(result.data.message)
          }
          break
        case 'profile':
          this.profileVisible = true
          break
        case 'history':
          const userInfo = this.getCookeieUserInfo()
          const result1 = await http_profile.getProfileInfo(userInfo.userId)
          if (result1.data.code === 200) {
            this.historyProfileList = JSON.parse(
              result1.data.data.historyProfile
            ).reverse()
            this.historyProfileVisible = true
            this.setCookeieUserInfo(
              'historyProfile',
              JSON.parse(result1.data.data.historyProfile).reverse()
            )
          } else {
            this.$message.error(result1.data.message)
          }

          break
      }
    },
    // 点击了修改用户名的确认按钮
    async updateUsernameCommit() {
      if (!(this.user.username === this.profile.username)) {
        const userInfo = this.getCookeieUserInfo()
        const result = await http_user.updateUsername({
          userId: userInfo.userId,
          username: this.user.username,
        })
        if (result.data.code === 200) {
          this.$message({
            message: '修改用户名成功',
            type: 'success',
          })
          this.usernameVisible = false
          this.profile.username = this.user.username
          this.setCookeieUserInfo('username', this.user.username)
        } else {
          this.$message.error(result.data.message)
        }
      }
    },
    // 点击了修改密码的确认按钮
    async updatePasswordCommit() {
      if (
        this.user.oldPassword === '' ||
        this.user.password === '' ||
        this.user.checkPassword === ''
      ) {
        this.$message.error('请把信息填写完整')
        return
      }
      if (this.user.password !== this.user.checkPassword) {
        this.$message.error('新密码两次不一致')
        return
      }
      const userInfo = this.getCookeieUserInfo()
      const result = await http_user.updatePassword(
        userInfo.userId,
        this.user.oldPassword,
        this.user.password
      )
      if (result.data.code === 200) {
        this.$message({
          message: '修改密码成功',
          type: 'success',
        })
        this.passwordVisible = false
        this.user.oldPassword = ''
        this.user.password = ''
        this.user.checkPassword = ''
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 修改电话中的发送原始手机电话号码
    async sendOldSmsCode() {
      const result = await http_register.sendCode(this.user.oldPhone)
      if (result.data.code === 200) {
        this.$message({
          message: '发送成功',
          type: 'success',
        })
        this.user.oldSmsCode = result.data.data
        // 启动短信倒计时
        this.user.OldCodeFlag = false
        let time = 60
        let timer = setInterval(() => {
          time--
          this.user.OldCodeText = time
          if (time === 0) {
            this.user.OldCodeFlag = true
            this.user.OldCodeText = '验证码'
            clearInterval(timer)
          }
        }, 1000)
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 修改电话中发送新手机电话号码
    async sendNewSmsCode() {
      let reg_phone = /^1[3-9]\d{9}$/
      if (!reg_phone.test(this.user.newPhone)) {
        this.$message.error('手机号输入不正确')
        return
      }
      const result = await http_register.sendCode(this.user.newPhone)
      if (result.data.code === 200) {
        this.$message({
          message: '发送成功',
          type: 'success',
        })
        this.user.newSmsCode = result.data.data
        // 启动短信倒计时
        this.user.NewCodeFlag = false
        let time = 60
        let timer = setInterval(() => {
          time--
          this.user.NewCodeText = time
          if (time === 0) {
            this.user.NewCodeFlag = true
            this.user.NewCodeText = '验证码'
            clearInterval(timer)
          }
        }, 1000)
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 点击了修改电话的确认按钮
    async updatePhoneCommit() {
      if (this.user.oldSmsCode === '') {
        this.$message.error('请发送旧手机的验证码')
        return
      }
      if (this.user.newSmsCode === '') {
        this.$message.error('请发送新手机的验证码')
        return
      }
      if (this.user.oldSmsCode !== this.user.oldSmsCodeInput) {
        this.$message.error('旧手机验证码不正确')
        return
      }
      if (this.user.newSmsCode !== this.user.newSmsCodeInput) {
        this.$message.error('新手机验证码不正确')
        return
      }
      const userInfo = this.getCookeieUserInfo()
      const result = await http_user.updatePhone(
        userInfo.userId,
        this.user.newPhone
      )
      if (result.data.code === 200) {
        this.$message({
          message: '修改成功',
          type: 'success',
        })
        this.phoneVisible = false
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 只显示电话的前三位和后四位
    hidePhone(iphone) {
      return (
        iphone.substring(0, 3) + '****' + iphone.substring(iphone.length - 4)
      )
    },
    // 修改头像方法
    async handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      if (res.code === 200) {
        this.$message({
          message: '头像上传成功',
          type: 'success',
        })
        if (this.imageList.length > 0) {
          // 删除之前上传的图片
          const result = await http_profile.deleteProfile(this.imageList[0])
          console.log(result)
          if (result.data.code === 200) {
            this.imageList = []
            this.imageList.push(res.data)
          } else {
            this.$message.error(result.data.message)
            return
          }
        } else {
          this.imageList.push(res.data)
        }
      }
    },
    // 点击修改头像确认按钮
    async updateProfileCommit() {
      if (this.imageList.length == 0) {
        this.$message.error('请上传头像')
        return
      }
      const userInfo = this.getCookeieUserInfo()
      const result = await http_profile.updateProfile(
        userInfo.userId,
        this.imageList[0]
      )
      if (result.data.code === 200) {
        this.$message({
          message: '头像修改成功',
          type: 'success',
        })
        const imagesList = result.data.data.split('&')
        this.profile.images = imagesList[0]
        this.setCookeieUserInfo('profile', imagesList[0])
        this.setCookeieUserInfo(
          'historyProfile',
          JSON.stringify(JSON.parse(imagesList[1]).reverse())
        )
        this.imageUrl = ''
        this.imageList = []
        this.profileVisible = false
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 点击修改头像取消按钮
    async updateProfileCancel() {
      this.imageUrl = ''
      if (this.imageList.length > 0) {
        const result = await http_profile.deleteProfile(this.imageList[0])
        if (result.data.code === 200) {
          this.imageList = []
          this.profileVisible = false
        } else {
          this.$message.error(result.data.message)
        }
      } else {
        this.profileVisible = false
      }
    },
    // 修改头像方法
    // 历史头像方法
    // 点击修改头像确认按钮
    async historyProfileCommit() {
      if (this.checkProfile === 0) {
        this.historyProfileVisible = false
      } else {
        const profile = this.historyProfileList[this.checkProfile]
        this.historyProfileList[this.checkProfile] = this.historyProfileList[0]
        this.historyProfileList[0] = profile

        const historyProfileListCopy = this.historyProfileList.reverse()

        const userInfo = this.getCookeieUserInfo()
        const result = await http_profile.updateHistoryProfile(
          userInfo.userId,
          historyProfileListCopy
        )
        if (result.data.code === 200) {
          this.$message({
            message: '头像修改成功',
            type: 'success',
          })
          this.profile.images = profile
          this.setCookeieUserInfo(
            'historyProfile',
            JSON.stringify(this.historyProfileListCopy)
          )
          this.setCookeieUserInfo('profile', profile)
          this.historyProfileVisible = false
        } else {
          this.$message.error(result.data.message)
        }
      }
    },
    // 点击修改头像取消按钮
    historyProfileCancel() {
      this.checkProfile = 0
      this.historyProfileVisible = false
    },
    // 历史头像方法
    // 调换到education页面
    goCourseList() {
      if (!(this.$route.path === '/education')) {
        this.$router.push('/education')
      }
    },
  },
  created() {
    const userInfo = this.getCookeieUserInfo()
    if (userInfo !== undefined) {
      this.profile.username = userInfo.username
      this.profile.images = userInfo.profile
      this.isLogin = true
    } else {
      this.isLogin = false
    }
  },
}
</script>

<style lang="scss">
.Header-box {
  font-size: 20px;
  width: 90%;
  margin: 25px auto;

  ul {
    display: flex;
    list-style-type: none;
    li {
      margin: 0 0px;
      .my {
        cursor: pointer;
      }
      .my:hover {
        color: #00a4ff;
        text-decoration: underline;
      }
    }
  }
  .content {
    margin-top: 15px;
    li {
      margin: 0 10px;
      .active:hover {
        color: #00a4ff;
        text-decoration: underline;
      }
      .active {
        color: black;
      }
    }
  }
  .search {
    margin-left: 40px;
    display: flex;
    .input {
      width: 350px;
      height: 30px;
      padding: 10px;
      font-size: 20px;
      border: 2px solid #00a4ff;
    }
    .button {
      cursor: pointer;
      width: 60px;
      height: 53px;
      background-color: #00a4ff;
      .icon {
        margin-top: 5px;
        margin-left: 5px;
        width: 40px;
        height: 40px;
      }
    }
  }
  .userInfo {
    display: flex;
    margin-left: 40px;
    .login {
      cursor: pointer;
      color: #000;
      text-decoration: none;
    }
    .login:hover {
      color: #00a4ff;
      text-decoration: underline;
    }
    .profile {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
      cursor: pointer;
    }
    .name {
      font-size: 16px;
      margin-top: 20px;
      width: 120px;
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload {
  border: 1px dashed #d9d9d9 !important;
  margin-left: 250px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff !important;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
